package cool.tsy.emos.wx.aop;

import cool.tsy.emos.wx.common.util.R;
import cool.tsy.emos.wx.config.shiro.ThreadLocalToken;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: hongxuan.wang
 * @date: Created in 2021/9/28 19:05
 * @description: 用来向 response 中添加 token 的切面类
 * @mail: 1443424326@qq.com
 */
@Aspect
@Component
public class TokenAspect {

    @Autowired
    private ThreadLocalToken threadLocalToken;

    @Pointcut("execution(public * cool.tsy.emos.wx.controller.*.*(..))")
    public void aspect() {

    }

    @Around("aspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 方法执行结果
        R r = (R) joinPoint.proceed();
        String token = threadLocalToken.getToken();
        // 如果ThreadLocal中存在token，说明是更新的token
        if (token != null) {
            // 往响应中放置token
            r.put("token", token);
            threadLocalToken.clear();
        }
        return r;
    }
}
